package com.tarry.nio;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

/**
 * 通过NIO将文本内容写入文件
 */
public class FileOutputChannel {

    public static void main(String[] args) {
        final File file = new File("./nio_test.txt");
        String content = "《鹧鸪天·醉拍春衫惜旧香》\n" +
                "宋·晏几道\n" +
                "醉拍春衫惜旧香。天将离恨恼疏狂。\n" +
                "年年陌上生秋草，日日楼中到夕阳。\n" +
                "云渺渺，水茫茫。征人归路许多长。\n" +
                "相思本是无凭语，莫向花笺费泪行。\n" +
                "\n" +
                "《蝶恋花·伫倚危楼风细细》\n" +
                "宋·柳永\n" +
                "伫倚危楼风细细，望极春愁，黯黯生天际。\n" +
                "草色烟光残照里，无言谁会凭阑意。\n" +
                "拟把疏狂图一醉，对酒当歌，强乐还无味。\n" +
                "衣带渐宽终不悔，为伊消得人憔悴。\n" +
                "\n" +
                "《清平乐·红笺小字》\n" +
                "宋·晏殊\n" +
                "红笺小字，说尽平生意。\n" +
                "鸿雁在云鱼在水，惆怅此情难寄。\n" +
                "斜阳独倚西楼，遥山恰对帘钩。\n" +
                "人面不知何处，绿波依旧东流。\n" +
                "\n" +
                "《浣溪沙·细雨斜风作晓寒》\n" +
                "宋·苏轼\n" +
                "元丰七年十二月二十四日，从泗州刘倩叔游南山\n" +
                "细雨斜风作晓寒，淡烟疏柳媚晴滩。\n" +
                "入淮清洛渐漫漫。\n" +
                "雪沫乳花浮午盏，蓼茸蒿笋试春盘。\n" +
                "人间有味是清欢。\n" +
                "\n" +
                "《一剪梅·红藕香残玉簟秋》\n" +
                "宋·李清照\n" +
                "红藕香残玉簟秋。轻解罗裳，独上兰舟。\n" +
                "云中谁寄锦书来？雁字回时，月满西楼。\n" +
                "花自飘零水自流。一种相思，两处闲愁。\n" +
                "此情无计可消除，才下眉头，却上心头。";
        try (FileOutputStream fileOutputStream = new FileOutputStream(file)) {
            final FileChannel channel = fileOutputStream.getChannel();
            final ByteBuffer allocate = ByteBuffer.allocate(1024);
            allocate.put(content.getBytes(StandardCharsets.UTF_8));
            // 翻转
            allocate.flip();
            channel.write(allocate);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
